/****************************************************
 * Copyright (c) 2015 SJXT Technology Limited, All rights reserved.
 *
 * No part of this program may be reproduced, transmitted,
 * transcribed, stored in a retrieval system, or translated into any 
 * other computer languages in any form or by any means without the
 * prior written permission of:
 *
 *   SJXT.CO.LTD.
 *   540, JinNing Road, Xiangzhou Zhuhai, GD 
 *   P.R. China
 *   Tel:       (+86)756-2274333
 *   Fax:       (+86)756-2282339
 **************************************************/
package com.zhao.pay;


import java.util.SortedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhao.base.TokenThread;
import com.zhao.util.MD5Util;

import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;


/**
 * 
 * @author zhaowj
 * @date2018年3月14日 下午9:45:03
 */
public class MysteriousUtil {
	private static Logger log=LoggerFactory.getLogger(MysteriousUtil.class);
     
	public static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb=new StringBuffer();
		sb.append("<xml>");
		Set es=parameters.entrySet();
	    Iterator it=es.iterator();
		while(it.hasNext())
		{
			Map.Entry entry=(Map.Entry)it.next();
			String k=(String)entry.getKey();
			String v=(String)entry.getValue();
			if("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k))
			{
				sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
			}
			else
			{
				sb.append("<"+k+">"+v+"</"+k+">");
			}	
		}
		sb.append("</xml>");
		return sb.toString();
	}
     
     public static String getNoncestr() {
		Random random=new Random();
		String temp=MD5Util.MD5Encode(String.valueOf(random.nextInt(1000)), "GBK").toLowerCase().replaceAll("s", "S");
		log.debug("Noncestr================"+temp);
		return temp;
	}
     
     public static String createSign(String characterEncoding,SortedMap<Object, Object> parameters) {
    	 StringBuffer sb =new StringBuffer();
    	 Set es =parameters.entrySet();
    	 Iterator it=es.iterator();
    	 while (it.hasNext()) {
			Map.Entry entry=(Map.Entry)it.next();
			String k=(String) entry.getKey();
			Object v=entry.getValue();
			if(v!=null&&!v.equals("")&&!"sign".equals(k)&&!"key".equals(k))
			{
				sb.append(k+"="+v+"&");
				
			}
			
		}
    	 sb.append("key="+TokenThread.api_key);
		String sign=MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		log.debug("sign================"+sign);
    	 return sign;
	}
     
     public static String setXML(String return_code,String return_msg) {
 		return "<xml><return_code><![CDATA["+return_code
 				+"]]></return_code><return_msg><!CDATA["+return_msg
 				+"]]></return_msg></xml>";
 	}
}
